package com.yrihr.wisdom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yrihr.wisdom.entity.ColumnType;
import com.yrihr.wisdom.entity.UploadEntity;
import com.yrihr.wisdom.mapper.UploadMapper;
import com.yrihr.wisdom.mapper.UploadTypeMapper;
import com.yrihr.wisdom.service.FileUploadService;
import com.yrihr.wisdom.util.FileUploadUtils;
import com.yrihr.wisdom.util.FileUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName : FileUploadServiceImpl
 * @Description :
 * @Author : wind
 * @Date: 2020-12-01 10:26
 * @Version 1.0
 */
@Service
@RequiredArgsConstructor
public class FileUploadServiceImpl extends ServiceImpl<UploadMapper, UploadEntity> implements FileUploadService {

    private final UploadMapper uploadMapper;
    private final UploadTypeMapper uploadTypeMapper;

    @Override
    public Integer upload(MultipartFile[] files, String baseDir, String name, String depiction, Integer columnType) throws Exception {
        //就算什么也不传，controller层的file也不为空，但是originalFilename会为空（亲测）
        Integer insertCount = 0;
        Integer count = 0;
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String originalFilename = file.getOriginalFilename();

                if (originalFilename == null || "".equals(originalFilename)) {
                    throw new Exception("上传文件不能为空");
                }
                //检测是否上传过同样的文件，如果有的话就删除。（这边可根据个人的情况修改逻辑）
                QueryWrapper<UploadEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("old_name", originalFilename);
                UploadEntity oldEntity = (UploadEntity) uploadMapper.selectOne(queryWrapper);

                //新的文件
                UploadEntity uploadEntity = new UploadEntity();
                uploadEntity.setOldName(file.getOriginalFilename());        //这边可以根据业务修改，项目中不要写死
                uploadEntity.setName(name);
                uploadEntity.setDescription(depiction);
                uploadEntity.setType(columnType == null ? 1 : columnType);
                String fileLocation = null;
                if (baseDir != null) {
                    fileLocation = FileUploadUtils.upload(baseDir, file);
                } else {
                    fileLocation = FileUploadUtils.upload(file);
                }

                uploadEntity.setLocation(fileLocation);
                insertCount = uploadMapper.insert(uploadEntity);

                if (oldEntity != null && insertCount == 1) {
                    //确保新的文件保存成功后，删除原有的同名文件(实体文件 and 数据库文件)
                    FileUtils.deleteFile(oldEntity.getLocation());
                    uploadMapper.deleteById(oldEntity.getId());
                    count++;
                }
                if (oldEntity == null && insertCount == 1) {
                    count++;
                }
            }
        }
        if (files.length == count && count != 0) {
            return count;
        } else {
            return 0;
        }

    }

    @Override
    public void download(HttpServletResponse response, String id) throws IOException {
        QueryWrapper<UploadEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        UploadEntity uploadEntity = (UploadEntity) uploadMapper.selectOne(queryWrapper);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");        //这边可以设置文件下载时的名字，我这边用的是文件原本的名字，可以根据实际场景设置
        response.setHeader("filename", URLEncoder.encode(uploadEntity.getOldName(), "UTF-8"));
        FileUtils.writeBytes(uploadEntity.getLocation(), response.getOutputStream());

    }

    /**
     * 查询所有类型
     *
     * @return
     */
    @Override
    public List<ColumnType> selectAllType() {
        QueryWrapper<ColumnType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "1");
        return uploadTypeMapper.selectAllType(queryWrapper);
    }

    /**
     * 根据type查询相应的upload列表
     *
     * @param type
     * @return
     */
    @Override
    public List<UploadEntity> selectUploadEntityList(Integer type) {
        QueryWrapper<UploadEntity> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("status","1");
        queryWrapper.eq("type", type);
        return uploadMapper.selectList(queryWrapper);
    }

    /**
     * 根据id查询UploadEntity信息，用作信息详情展示
     *
     * @param id
     * @return
     */
    @Override
    public UploadEntity selectUploadEntityById(long id) {
        return uploadMapper.selectById(id);
    }

    /**
     * 根据解码后的数字进行检测id是否存在
     *
     * @param id
     * @return
     */
    @Override
    public UploadEntity checkUploadEntityId(String id) {
        return uploadMapper.selectById(id);
    }

    @Override
    public IPage<UploadEntity> selectPage(long current, long limit, Integer type) {
        QueryWrapper<UploadEntity> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        wrapper.eq("type", type);
        Page<UploadEntity> page = new Page<UploadEntity>(current, limit);
        page = baseMapper.selectPage(page, wrapper);
        return page;
    }
}

